# 生产环境
import webbrowser
import json
import paramiko
import os
import subprocess
from script import *

remote_server = {'file_name': 'prod_deploy.py', 'env': 'prod', 'env_cname': '生产环境', 'web_url': 'http://192.168.2.20:8090/index', 'command': 'npm run build:prod', 'host': '192.168.2.20', 'port': 22, 'username': 'root', 'password': 'gydx@2024', 'pkey': 'None', 'remote_jar_path': '/root/nginx/bis',
                 'dist_name': 'prod_dist'}

with open('./generate-deploy-const.json',
          'r',
          encoding='utf-8'
          ) as json_file:
    data = json.load(json_file)

# 读取配置数据
remote_server = data['server_config']['prod_remote_server']
work_dir = 'aaa'
local_jar_path = 'aaa' + remote_server['dist_name']
remote_jar_path = remote_server['remote_jar_path']
os.chdir(work_dir)
process = subprocess.run(remote_server['command'],
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         universal_newlines=True
                         )
if remote_server['pkey']:
    tprivate_key = paramiko.RSAKey.from_private_key_file(remote_server['pkey'])
else:
    tprivate_key = None

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_server['host'],
            remote_server['port'],
            remote_server['username'],
            password=remote_server['password'],
            pkey=private_key
            )
sftp = ssh.open_sftp()

# 上传
upload_dir(sftp,
           local_jar_path,
           remote_jar_path
           )

# 释放
sftp.close()
ssh.close()

# 打开地址
webbrowser.open_new(remote_server['web_url'])
